<?php

namespace app\service;

use app\exception\ModelEmptyException;
use app\exception\ModelException;
use app\model\Advertisement;
use app\model\Attachment;
use app\model\Category;
use app\model\Link;
use app\model\Model;
use app\model\Nav;
use app\model\Slide;
use app\model\SysSetting;
use app\model\WebsiteSetting;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\facade\Log;

class ApiService
{

    /**
     * @throws ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public static function getAdvertisement($id, $sellerId)
    {
        $Advertisement = new Advertisement();
        $attachWhere = [
            ['id','=',$id],
            ['seller_id','=',$sellerId],
            ['expiration_date','>',date('Y-m-d',time())]
        ];
       return $Advertisement->getAdvertisement($attachWhere,'id,attachment_id,title,url,type,expiration_date',['attachment'=>function($q){
           $q->field('id,name,type,url');
       }])['data']->toArray();
    }


    /**
     * 配置列表
     * @throws ModelException
     * @throws ModelEmptyException
     */
    public static function tagSetting($param)
    {
        if($param['type'] == 1){
            // 系统配置
            $companyCacheKey = 'hc_company_'.$param['sellerId'];
            $siteData = cache($companyCacheKey);
            if(isset($siteData[$param['name']])){
                $setting = $siteData[$param['name']];
            }else{
                $SysSetting = new SysSetting();
                $setting = $SysSetting->getSysSetting(['seller_id'=>$param['sellerId'],'title'=>$param['name']])['data'];
                if(!empty($setting)){
                    $setting = $setting['value'];
                    Cache::set($companyCacheKey,$setting);
                }else{
                    $setting = '';
                }
            }
        }else{
            $siteCacheKey = $param['sellerId'] .'_'.$param['siteId'] .'_'. $param['lang'] . '_website_cache_key';
            $siteData = cache($siteCacheKey);
            if(!empty($siteData)){
                $setting = $siteData[$param['name']];
            }else{
                $settingData = self::setWebsiteSetting($param['sellerId'],$param['siteId'], $param['lang']);
                if(!empty($settingData)){
                    if(!empty($settingData[$param['name']])){
                        $setting = $settingData[$param['name']];
                    }else{
                        $setting = '';
                    }
                }else{
                    $setting = '';
                }
                Cache::set($siteCacheKey,$settingData);
            }
        }
        return $setting;
    }
    /**
     * @throws ModelException
     * @throws ModelEmptyException
     */
    public static function setWebsiteSetting($sellerId,$siteId,$lang)
    {
        // 网站配置
        $siteCacheKey = $sellerId .'_'.$siteId.'_'. $lang . '_website_cache_key';
        $siteData = cache($siteCacheKey);
        $settingData = [];
        if(empty($siteData)){
            $WebsiteSetting = new WebsiteSetting();
            $setting = $WebsiteSetting->getWebsiteSetting(['seller_id'=>$sellerId,'website_id'=> $siteId,'lang'=>$lang])['data']->toArray();
            $settingData= json_decode($setting['setting'],true);
            if(!empty($settingData['logo'])){
                $attachment = new Attachment();
                $attach = $attachment->getAttachment(['id'=>$settingData['logo'],'seller_id'=>$sellerId])['data'];
                if(!empty($attach)){
                    $settingData['logo'] = $attach['url'];
                }else{
                    $settingData['logo'] = '';
                }
            }
            if(!empty($settingData['wechat_code'])){
                $attachment = new Attachment();
                $attach = $attachment->getAttachment(['id'=>$settingData['wechat_code'],'seller_id'=>$sellerId])['data'];
                if(!empty($attach)){
                    $settingData['wechat_code'] = $attach['url'];
                }else{
                    $settingData['wechat_code'] = '';
                }
            }
            if(!empty($settingData['dark_logo'])){
                $attachment = new Attachment();
                $attach = $attachment->getAttachment(['id'=>$settingData['dark_logo'],'seller_id'=>$sellerId])['data'];
                if(!empty($attach)){
                    $settingData['dark_logo'] = $attach['url'];
                }else{
                    $settingData['dark_logo'] = '';
                }
            }
            Cache::set($siteCacheKey,$settingData);
        }
        return $settingData;

    }

    /**
     * @throws \app\exception\ModelEmptyException
     * @throws ModelException
     */
    public static function getBreadcrumb($cid,$sellerId, $siteId, $lang): array
    {

        $Category = new Category();
        $category= $Category->getCategory(['id'=>$cid,'seller_id'=>$sellerId,'lang'=>$lang],[],'id,title,path')['data']->toArray();
        $categoryPath = $category['path'];
        $ids = explode('-',$categoryPath);
        array_shift($ids);

        if(!empty($ids)){
            $catesWhere = [
                ['id','in',$ids],
                ['seller_id','=',$sellerId],
//                ['website_id','=',$siteId],
                ['lang','=',$lang],
                ['status','=',1]
            ];
            $cates = $Category->getAllCustomData($catesWhere,'id desc','id,title')['data'];
            // 按照ids的顺序排序
            $data = [];
            foreach($cates as $key => $val){
                if($val['id'] == $ids[$key]){
                    array_push($data,$val);
                }
            }
            array_push($data,$category);
        }else{
            $data = [$category];
        }
        return $data;
    }



    /**
     * 返回指定分类下的所有子分类
     * @param $pid
     * @param $siteId
     * @param $sellerId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelException
     * @throws ModelNotFoundException
     */
    public static function getAllSubCategory($pid,$sellerId,$siteId,$lang,$maxLevel,$sort,$field,$isTree = true,$with=''): array
    {
        Log::record(microtime(true));
        $Category = new Category();
        $categoryId = intval($pid);
        if ($pid !== 0) {
            $category= $Category->where(['id'=>$categoryId,'website_id'=>$siteId,'seller_id'=>$sellerId,'lang'=>$lang])->find();
            $categoryPath = $category['path'] .$categoryId . '-';
        } else {
            $categoryPath = 0 . '-';
        }
        $where = [
            'seller_id'   => $sellerId,
            'website_id'    => $siteId,
            'lang'  => $lang,
            'status'      => 1,
        ];
        $with = self::setCateWith($with,$field);
        try{
            $res = $Category->field($field)->with($with)->where($where)->whereLike('path', "$categoryPath%")->order($sort)->select()->toArray();
        }catch(\Exception $e){
            throw new ModelException($e->getMessage());
        }
        $res = self::getTreeData($res,$pid,$maxLevel);
        Log::record(microtime(true));
        return $res;
    }

    /**
     * 分类详情
     * @throws ModelException
     */
    public static function getCategory($id, $sellerId, $siteId, $lang, $field='*', $with=''): array
    {
        $Category= new Category();
        $where = [
            'id' => $id,
            'seller_id'   => $sellerId,
            'website_id'   => $siteId,
            'lang'  => $lang,
            'status'      => 1,
        ];
        $with = self::setCateWith($with,$field);
        try{
            $cate = $Category->field($field)->with($with)->where($where)->findOrEmpty()->toArray();
        }catch(\Exception $e){
            throw new ModelException($e->getMessage());
        }
        return $cate;
    }

    /**
     * 子分类
     * @throws ModelException
     */
    public static function getSubCategory($pid, $sellerId, $siteId, $lang, $sort,$limit,$field='*', $with=''): array
    {
        $Category= new Category();
        if(empty($pid)){
            return [];
        }
        $pidArr = explode(',',$pid);
        if(count($pidArr) == 1){
            $where = [
                'parent_id' => $pidArr[0],
                'seller_id'   => $sellerId,
                'website_id'   => $siteId,
                'lang'  => $lang,
                'status'  => 1,
            ];
        }else{
            $where = [
                ['parent_id' ,'in', $pidArr],
                ['seller_id' ,'=', $sellerId],
                ['website_id'  ,'=', $siteId],
                ['lang'  ,'=', $lang],
                ['status' , '=' ,1],
            ];
        }
        $with = self::setCateWith($with,$field);
        try{
            if($limit == 'all'){
                $cate = $Category->field($field)->with($with)->where($where)->order($sort)->select()->toArray();
            }else{
                $cate = $Category->field($field)->with($with)->where($where)->order($sort)->limit($limit)->select()->toArray();
            }
        }catch(\Exception $e){
            throw new ModelException($e->getMessage());
        }
        return $cate;
    }

    /**
     * 返回符合条件的所有分类
     * @param array $param
     * @return array
     * @throws ModelException
     */
    public static function getCategoryList($ids,$sellerId,$siteId,$lang,$sort='sort asc',$field='*',$with=''): array
    {
        $Category= new Category();
        $where = [
            'seller_id'   => $sellerId,
            'website_id'   => $siteId,
            'lang'  => $lang,
            'status'      => 1,
        ];
        $with = self::setCateWith($with,$field);
        $temp = $Category
            ->field($field)
            ->with($with)
            ->where($where)
            ->order($sort);
        if(!empty($ids)){
            $whereIn = explode(',',$ids);
            $temp = $temp->whereIn('id',$whereIn);
        }else{
            return [];
        }
        try{
            $res = $temp->select()->toArray();
        }catch(\Exception $e){
            throw new ModelException($e->getMessage());
        }
        return $res;

    }

    /**
     * 导航列表
     * @throws \app\exception\ModelException
     * @throws ModelEmptyException
     */
    public static function nav($cid, $siteId, $sellerId,$lang,$maxLevel,$pid=0,$sort="sort desc"): array
    {
        $Nav = new Nav();
        $where = [
            'seller_id'=>$sellerId,
            'nav_cate_id'=>$cid,
            'website_id'=>$siteId,
            'lang'  => $lang,
            'status'    => 1
        ];
//        $navCacheKey = 'hc_' . $sellerId . '_' . $cid . '_' .$pid. '_' . $siteId .'_'. $maxLevel .'_'.$lang. '_nav';
//        $navData = json_decode(cache($navCacheKey),true);
        $navData = null;

        if(!empty($navData)){
            $nav = $navData;
        }else{
            if(!empty($pid)){
                $where['parent_id'] = $pid;
            }
            $nav = $Nav->with(['category.thumbnail'])->where($where)->order($sort)->select()->each(function(&$item){
                if($item['type'] == 2){
                    if(!empty($item['category'])){
                        if($item['category']['type'] == 3){
                            $item['href'] =$item['category']['alias'];
                        }else if($item['category']['type'] == 2){
                            $item['href'] = 'javascript:;';
                        }else{
                            if($item['category']['alias'] == '/'){
                                $item['href'] = $item['category']['alias'];
                            }else{
                                $item['href'] = url('List/index?id='.$item['category']['id'],[],true);
                            }
                        }
                    }
                }
            })->toArray();
            if(empty($nav)){
                $nav = [];
            }else{
                $nav = makeTreeWithMaxLevel($nav,$pid,$maxLevel);
//                Cache::set($navCacheKey,json_encode($nav));
            }
        }
        return $nav;
    }

    /**
     * 幻灯片
     * @throws ModelException
     */
    public static function slide($cid, $sellerId,$lang,$field,$limit,$order): array
    {
        $Slide = new Slide();
        $where = [
            'seller_id'=>$sellerId,
            'lang'   => $lang,
            'slide_cate_id'   => $cid,
            'status' => 1
        ];
        $tmp = $Slide->with(['attachment'=>function($q){
            $q->field('id,name,url,type');
        }])->field($field)->where($where)->order($order);
        if(!empty($limit)){
            $tmp->limit($limit);
        }
        return $tmp->select()->toArray();
    }

    /**
     * 友情链接
     * @throws ModelException
     */
    public static function link($ids,$siteId, $sellerId,$lang,$type,$field,$limit,$order)
    {
        $Nav = new Link();
        $where = [
            'seller_id'=>$sellerId,
            'website_id'=>$siteId,
            'type' => $type,
            'is_del' => 1
        ];
        $link = $Nav->field($field)->where($where);
        if(!empty($ids)){
            $ids = explode(',',$ids);
            $link = $link -> whereIn('id',$ids);
        }
        if(empty($limit)){
            $link = $link->limit((int)$limit);
        }
        
        return $link->order($order)->select()->toArray();

    }

    /**
     * 分类关联设置
     * @param $with
     * @return string[]
     */
    public static function setCateWith($with,$field = '*'): array
    {
        if($field == '*'){
            $default = [
                'thumbnail' => function($q){
                    $q->field('id,name,type,url');
                },'banner' => function($q){
                    $q->field('id,name,type,url');
                }
            ];
        }else{
            $default = [];
            $field =  explode(',',$field);
            if(in_array('thumbnail',$field)){
                $default = self::setMainImageWith('thumbnail',[]);
            }
            if(in_array('banner',$field)){
                $default = self::setMainImageWith('banner',$default);
            }
        }
        if(empty($with)){
            $with = $default;
        }else{
            $with = explode(',',$with);
            $with =  array_merge($default,$with);
        }
        return $with;
    }
    // 主表附件关联设置
    public static function setMainImageWith($imgKey,$default = []): array
    {
        $tmpWith =  [
            $imgKey => function($q){
                $q->field('id,name,url,type');
            }
        ];
        return array_merge($default,$tmpWith);
    }

    public static function getTreeData($data,$pid,$maxLevel): array
    {
        if(empty($data)){
            $data = [];
        }else{
            $data = makeTreeWithMaxLevel($data,$pid,$maxLevel);
        }
        return $data;
    }

}
